<template>
  <div class="form-container">
    <el-form
        label-width="auto"
        :model="formLabelAlign"
        class="login-form"
    >
      <h2>Login</h2>

      <el-form-item label="Username" label-position="left">
        <el-input v-model="formLabelAlign.username" placeholder="Enter your username" />
      </el-form-item>

      <el-form-item label="Password">
        <el-input
            v-model="formLabelAlign.password"
            placeholder="Enter your password"
            type="password"
        />
      </el-form-item>

      <el-button @click="handleAuth" type="primary" block>
        登录
      </el-button>

      <div v-if="loginError" class="error-message">
        登录失败，请检查用户名和密码！
      </div>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import request from '../../utils/request';
import router from '../../router';

const formLabelAlign = reactive({
  username: '',
  password: '',
});

const isLoggedIn = ref(false); // 用来跟踪用户是否登录
const loginError = ref(false); // 登录失败的错误提示

// 登录/退出功能
function handleAuth() {
  request.post('/api/user/user/login', {
    userName: formLabelAlign.username,
    password: formLabelAlign.password,
  })
      .then((res) => {
        localStorage.setItem('token', res.data.data.token);
        isLoggedIn.value = true; // 设置登录状态为 true
        loginError.value = false; // 清除错误提示
        console.log('登录成功, Token:', res.data.data.token);
        router.push('/default');
        window.location.reload();
      })
      .catch((err) => {
        console.log('登录失败', err);
        loginError.value = true; // 设置错误提示为显示
      });
}

// 在组件挂载时检查用户是否已登录
if (localStorage.getItem('token')) {
  isLoggedIn.value = true;
  router.push('/default');
}
</script>

<style scoped>
/* 父容器：让内容居中 */
.form-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

/* 表单元素：添加额外样式 */
.el-form {
  padding: 30px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
  text-align: center;
}

/* 表单标题样式 */
h2 {
  font-size: 24px;
  margin-bottom: 20px;
}

/* 输入框样式 */
.el-input {
  margin-bottom: 15px;
}

/* 按钮样式 */
.el-button {
  margin-top: 20px;
}

/* 错误消息样式 */
.error-message {
  margin-top: 10px;
  color: red;
  font-size: 14px;
}

/* 使按钮全宽 */
.el-button[block] {
  width: 100%;
}
</style>



